home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9060 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: newshost.lanl.gov!tanmoy
  2. From: tanmoy@qcd.lanl.gov (Tanmoy Bhattacharya)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: revised code of calling a function twice from printf
  5. Date: 05 Mar 1996 03:44:09 GMT
  6. Organization: Los Alamos National Laboratory
  7. Distribution: world
  8. Message-ID: <TANMOY.96Mar4204409@qcd.lanl.gov>
  9. References: <4hfs54$k4e@newsbf02.news.aol.com>
  10.     <Pine.A32.3.91.960304174215.96209J-100000@black.weeg.uiowa.edu>
  11. NNTP-Posting-Host: qcd.lanl.gov
  12. Mime-Version: 1.0
  13. Content-Type: text
  14. In-reply-to: The Amorphous Mass's message of Mon, 4 Mar 1996 17:51:03 -0600
  15.  
  16. In article <Pine.A32.3.91.960304174215.96209J-100000@black.weeg.uiowa.edu>
  17. The Amorphous Mass <robinson@blue.weeg.uiowa.edu> writes:
  18. <snip>
  19. TAM:   You're returning a pointer to an automatic variable, which is 
  20. TAM: guaranteed bad news.
  21. <snip>
  22. TAM:       printf("[1] %s             [2] %s\n", /* both quotes on same line */
  23. TAM:         display_drug_type(0), display_drug_type(1));
  24. <snip>
  25. TAM: > char *display_drug_type(int drug_index) {
  26. <snip>
  27. TAM:      static char drug_type[81];  /* static variables are automatically
  28. TAM:                   initialized to 0, and it's safe to
  29. TAM:                   return their addresses -- they "persist" */
  30. <snip>
  31. TAM: >    return drug_type;
  32. TAM: > }
  33.  
  34. The program is still incorrect. No solution `works' and avoids memory
  35. leak without changing the call. So, simply use,
  36.  
  37. char first[80]={0}, second[80]={0};
  38. strncpy(first,display_drug_type(0),sizeof first - 1);
  39. strncpy(second,display_drug_type(1),sizeof second - 1);
  40. printf("[1] %s             [2] %s\n",first,second);
  41.  
  42. Many other solutions are possible: some cleaner than others. I would
  43. actually use malloc/free in this context.
  44.  
  45. Cheers
  46. Tanmoy
  47. --
  48. tanmoy@qcd.lanl.gov(128.165.23.46) DECNET: BETA::"tanmoy@lanl.gov"(1.218=1242)
  49. Tanmoy Bhattacharya O:T-8(MS B285)LANL,NM87545 H:#9,3000,Trinity Drive,NM87544
  50. Others see <gopher://yaleinfo.yale.edu:7700/00/Internet-People/internet-mail>,
  51. <http://alpha.acast.nova.edu/cgi-bin/inmgq.pl>or<ftp://csd4.csd.uwm.edu/pub/
  52. internetwork-mail-guide>. -- <http://nqcd.lanl.gov/people/tanmoy/tanmoy.html>
  53. fax: 1 (505) 665 3003   voice: 1 (505) 665 4733    [ Home: 1 (505) 662 5596 ]
  54.